package com.example.demo.business.service;

import com.example.demo.base.bean.Meta;
import com.example.demo.base.exceptions.BaseException;
import com.example.demo.base.util.CommonUtil;
import com.example.demo.business.bean.dto.VideoListDto;
import com.example.demo.business.bean.entity.HStar;
import com.example.demo.business.bean.entity.HTease;
import com.example.demo.business.bean.entity.HUser;
import com.example.demo.business.bean.entity.HVideo;
import com.example.demo.business.bean.enums.AdType;
import com.example.demo.business.bean.enums.UserType;
import com.example.demo.business.bean.enums.WatchLimitType;
import com.example.demo.business.bean.vo.*;
import com.example.demo.business.dao.*;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Service
public class VideoService {
    @Autowired
    private HVideoDao hVideoDao;
    @Autowired
    private HStarDao hStarDao;
    @Autowired
    private AdService adService;
    @Autowired
    private HCategoryDao hCategoryDao;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private HTeaseDao hTeaseDao;

    public Object movieSearch(String searchKey, Pageable pageable){
        searchKey = "%"+searchKey+"%";
        return hVideoDao.findBySearchStrLike(searchKey,pageable).stream().map(item->{
            SearchMovieVo movieVo = new SearchMovieVo();
            BeanUtils.copyProperties(item,movieVo);
            movieVo.setIds(item.getId());
            movieVo.setDownUrl(item.getNormalVideoUrls());
            return movieVo;
        });
    }

    public Object getMovieDetail(String videoId,String token){
        //TODO 购买之后无线观看
        //TODO 限免减少观看次数
        HUser hUser = tokenService.getUserInfoByToken(token);
        int uid = hUser.getId();
        HVideo hVideo = hVideoDao.findById(Integer.parseInt(videoId)).orElseThrow(()->new BaseException(Meta.MovieNOTExist));

        VideoDetailVo videoItemVo = new VideoDetailVo();
        BeanUtils.copyProperties(hVideo,videoItemVo);
        videoItemVo.setId(hVideo.getId());
        videoItemVo.setVip(hVideo.getVip()!=0);
        videoItemVo.setHot(hVideo.getHot());
        videoItemVo.setType(hVideo.getType());
        videoItemVo.setName(hVideo.getName());
        videoItemVo.setLine1(hVideo.getNormalVideoUrls());
        videoItemVo.setDownUrl(hVideo.getNormalVideoUrls());
        videoItemVo.setLine2(hVideo.getNormalVideoUrls());
        videoItemVo.setCode(hVideo.getCode());
        videoItemVo.setWatchLimit(watchLimit(hUser,hVideo));
        videoItemVo.setVipLine(hVideo.getVipNormalVideoUrls());
        videoItemVo.setVipSuperLine(hVideo.getVipSuperVideoUrls());

        HTease hTease = hTeaseDao.findByUidAndVideoId(uid,hVideo.getId());
        videoItemVo.setUpOrLow(hTease==null?0:hTease.getType());

        //获取女星
        String[] stars = hVideo.getStars().split(",");
        List<StarItemVo> starList = new ArrayList<>();
        for (String starId:stars){
            if (starId.equals("")){
                break;
            }
            hStarDao.findById(Integer.parseInt(starId)).ifPresent(item->{
                StarItemVo starItemVo = new StarItemVo();
                starItemVo.setIds(item.getId());
                starItemVo.setName(item.getName());
                starItemVo.setImg(item.getImg());
                starList.add(starItemVo);
            });
        }
        //获取标签
        String[] labelIds = hVideo.getLabelIds().split(",");
        List<IndexCategoryVo> labelList = new ArrayList<>();
        for (String labelId:labelIds){
            hCategoryDao.findById(Integer.parseInt(labelId)).ifPresent(item->{
                IndexCategoryVo categoryVo = new IndexCategoryVo();
                categoryVo.setCid(item.getId());
                categoryVo.setCname(item.getName());
                labelList.add(categoryVo);
            });
        }

        //获取广告
        videoItemVo.setAdItem(adService.getDetailAd(AdType.Detail.num));
        //获取线路信息
        List<LineVo> lineVoList = getLineVos(hVideo);

        videoItemVo.setLabelList(labelList);
        videoItemVo.setLineVoList(lineVoList);
        videoItemVo.setStarList(starList);
        return videoItemVo;

    }

    //获取线路 TODO 弄真实的数据
    private List<LineVo> getLineVos(HVideo hVideo){
        //获取线路清晰度
        List<LineVo> lineVos = new ArrayList<>();
        String url = hVideo.getNormalVideoUrls();
        String[] arr = url.split("/");
        String fileName = arr[arr.length-1];
        String host = url.split(fileName)[0];

        if (hVideo.getType() == 1){
            List<ClarityVo> clarityVos = new ArrayList<>();
            clarityVos.add(new ClarityVo("标清",fileName,true));
//        clarityVos.add(new ClarityVo("高清",fileName,true));
//        clarityVos.add(new ClarityVo("超清",fileName,false));
            lineVos.add(new LineVo("线路1",host,false,clarityVos));

            List<ClarityVo> clarityVos1 = new ArrayList<>();
            clarityVos1.add(new ClarityVo("标清",fileName,true));
            clarityVos1.add(new ClarityVo("高清",fileName,true));
//        clarityVos1.add(new ClarityVo("超清",fileName,false));
            lineVos.add(new LineVo("线路2",host,false,clarityVos1));

            List<ClarityVo> clarityVos2 = new ArrayList<>();
            clarityVos2.add(new ClarityVo("标清",fileName,true));
            clarityVos2.add(new ClarityVo("高清",fileName,true));
            clarityVos2.add(new ClarityVo("超清",fileName,true));
            clarityVos2.add(new ClarityVo("蓝光",fileName,true));
            lineVos.add(new LineVo("Vip线路",host,true,clarityVos2));
        }else {
            //小视频就只有标清
            List<ClarityVo> clarityVos = new ArrayList<>();
            clarityVos.add(new ClarityVo("标清",fileName,true));
//        clarityVos.add(new ClarityVo("高清",fileName,true));
//        clarityVos.add(new ClarityVo("超清",fileName,false));
            lineVos.add(new LineVo("线路1",host,false,clarityVos));

//            List<ClarityVo> clarityVos1 = new ArrayList<>();
//            clarityVos1.add(new ClarityVo("标清",fileName,true));
////            clarityVos1.add(new ClarityVo("高清",fileName,true));
////            clarityVos1.add(new ClarityVo("超清",fileName,false));
//            lineVos.add(new LineVo("线路2",host,false,clarityVos1));


//            List<ClarityVo> clarityVos3 = new ArrayList<>();
//            clarityVos3.add(new ClarityVo("标清",fileName,true));
////            clarityVos1.add(new ClarityVo("高清",fileName,true));
////            clarityVos1.add(new ClarityVo("超清",fileName,false));
//            lineVos.add(new LineVo("线路3",host,false,clarityVos3));

//            List<ClarityVo> clarityVos2 = new ArrayList<>();
//            clarityVos2.add(new ClarityVo("标清",fileName,true));
////            clarityVos2.add(new ClarityVo("高清",fileName,true));
////            clarityVos2.add(new ClarityVo("超清",fileName,true));
//            lineVos.add(new LineVo("Vip线路",host,true,clarityVos2));
        }
        return lineVos;
    }

    //获取观看限制
    private int watchLimit(HUser hUser,HVideo hVideo){
        if (hUser.getVipType() != 0){
            return WatchLimitType.NO.num;
        }
        if (hVideo.getVip() == 1){
            return WatchLimitType.NotVip.num;
        }
        if (hUser.getRemainNum()<=0){
            return WatchLimitType.XianMian.num;
        }else {
            hUser.setRemainNum(hUser.getRemainNum()-1);
            tokenService.updateUserInfo(hUser);
            return WatchLimitType.NO.num;
        }
    }
    //
    public Object getRecommendedMovie(String videoId,String token,Pageable pageable){
        HVideo hVideo = hVideoDao.findById(Integer.parseInt(videoId)).orElseThrow(()->new BaseException(Meta.MovieNOTExist));
        int type = hVideo.getType();
        Stream<HVideo> videoStream  = hVideoDao.findByTypeOrderByCreatedAtDesc(type,pageable).get();
        List<VideoItemVo> videoList;
        if (videoStream == null){
            videoList = new ArrayList<>();
        }else {
            videoList = videoStream.map(item->{
                VideoItemVo videoItemVo = new VideoItemVo();
                BeanUtils.copyProperties(item,videoItemVo);
                videoItemVo.setIds(String.valueOf(item.getId()));
                videoItemVo.setImg(item.getShowImg());
                videoItemVo.setUpdateTime(CommonUtil.getTimeOld(item.getCreatedAt()));
                videoItemVo.setVip(item.getVip() != 0);
                return videoItemVo;
            }).collect(Collectors.toList());
        }
        return videoList;
    }
    public Object downVideo(String token,int videoId){
        Map<String,String> map = new HashMap<>();
        map.put("url","http://www.baidu.com");
        return map;
    }
    //
    public Object uporlow(String token,int videoId,int uporlow){
        int uid = tokenService.getUidByToken(token);
        HTease hTease = hTeaseDao.findByUidAndVideoId(uid,videoId);
        if (hTease==null){
            hTease= new HTease(videoId,uid,uporlow,System.currentTimeMillis()/1000,System.currentTimeMillis()/1000);
        }else {
            hTease.setType(uporlow);
//            throw new BaseException(Meta.HasUpErr);
        }
        hTeaseDao.save(hTease);

        //计算影片热度
        int up = hTeaseDao.countByTypeAndVideoId(1,videoId);
        int low = hTeaseDao.countByTypeAndVideoId(2,videoId);

        HVideo hVideo = hVideoDao.findById(videoId).get();
        if ((up+low)==0){
            hVideo.setHot(0);
        }else {
            hVideo.setHot(((float) up)*100/((float)up+(float)low));
        }
        hVideoDao.save(hVideo);
        //设置影片热度
        Map<String,String>  map = new HashMap<>();
        map.put("hot",String.valueOf(hVideo.getHot()));
        return map;
    }

    public Object getVideoList(int[] videoIds){
        List<HVideo> hVideos = new ArrayList<>();
        for (int videoId:videoIds){
            hVideoDao.findById(videoId).ifPresent(hVideos::add);
        }
        return hVideos.stream().map(item->{
            VideoItemVo videoItemVo = new VideoItemVo();
            BeanUtils.copyProperties(item,videoItemVo);
            videoItemVo.setIds(String.valueOf(item.getId()));
            videoItemVo.setImg(item.getShowImg());
            videoItemVo.setUpdateTime(CommonUtil.getTimeOld(item.getCreatedAt()));
            videoItemVo.setVip(item.getVip() != 0);
            return videoItemVo;
        }).collect(Collectors.toList());
    }

    //通过分类获取电影
    public Object getCategoryMovie(VideoListDto videoListDto, Pageable pageable){
        Stream<HVideo> videoStream = null;
        //特殊分类
        if (videoListDto.getCid() == 0){
            //查找VIP
            if ("vip".equals(videoListDto.getCname()) || "VIP".equals(videoListDto.getCname())){
                videoStream = hVideoDao.findByTypeAndVipOrderByCreatedAtDesc(videoListDto.getType(),1,pageable).get();
            }
            //查找最新
            if ("最新".equals(videoListDto.getCname())){
                videoStream = hVideoDao.findByTypeOrderByCreatedAtDesc(videoListDto.getType(),pageable).get();

            }
            //查找热门
            if ("热门".equals(videoListDto.getCname())){
                videoStream = hVideoDao.findByTypeOrderByHotDesc(videoListDto.getType(),pageable).get();
            }
        }else {
            String cidLike = "%"+videoListDto.getCid()+"%";
            if (videoListDto.isIshot()){
                //查找标签下的热门
                videoStream = hVideoDao.findByTypeAndLabelIdsLikeOrderByHotDesc(videoListDto.getType(),cidLike,pageable).get();
            }else {
                //查找标签下的分类 按时间排序
                videoStream = hVideoDao.findByTypeAndLabelIdsLikeOrderByCreatedAtDesc(videoListDto.getType(),cidLike,pageable).get() ;
            }
        }
        List<VideoItemVo> videoList;
        if (videoStream == null){
            videoList = new ArrayList<>();
        }else {
            videoList = videoStream.map(item->{
                VideoItemVo videoItemVo = new VideoItemVo();
                BeanUtils.copyProperties(item,videoItemVo);
                videoItemVo.setAdUrl("");
                videoItemVo.setIds(String.valueOf(item.getId()));
                videoItemVo.setImg(item.getShowImg());
                videoItemVo.setUpdateTime(CommonUtil.getTimeOld(item.getCreatedAt()));
                videoItemVo.setVip(item.getVip() != 0);
                videoItemVo.setDownUrl(item.getNormalVideoUrls());
                return videoItemVo;
            }).collect(Collectors.toList());
        }
//        VideoItemVo videoItemVo = new VideoItemVo(String.valueOf(0),"真人棋牌 在线赢钱","3小时前","http://192.168.0.127/img/ad/1.jpg",
//                "http://192.168.0.127/img/ad/1.jpg", "http://192.168.0.127/img/ad/2.jpg",true,
//                "http://192.168.0.127",0f,"",false,false,videoListDto.getType());

        if (videoListDto.isAd()){
            if (videoList.size()!=0){
                //首页 那么最前面显示一条广告
                VideoItemVo videoItemVo;
                if (videoList.size()>5){
                    videoItemVo = adService.getItemAd(videoListDto.getType());
                    if (videoItemVo !=null) videoList.add(4,videoItemVo);
                }
                if (videoList.size()>9){
                    videoItemVo = adService.getItemAd(videoListDto.getType());
                    if (videoItemVo !=null) videoList.add(7,videoItemVo);
                }
            }
        }

        return videoList;
    }

}
